<!--
 * @description: 登录页入口
 * @Author: Islands
 * @Date: 2023-05-31 15:18:34
 * @LastEditTime: 2024-03-25 20:12:49
-->
<script lang='ts' setup>
import { ref, reactive } from 'vue';
import { User, Lock } from '@element-plus/icons-vue';
import type { FormInstance } from 'element-plus';
import router from '@/router/index';
import { useAuthStore } from '@/store/index'
import { noChinese } from '@/utils/validate';
import { ILoginData } from '@/axios/login/types.d';

const formRef = ref<FormInstance>();
const loading = ref<boolean>(false);
const loginForm = reactive<ILoginData>({
    username: '',
    password: '',
});


/**
 * 登录方法
 * @param _loginFrom 
 */
const loginChange = (_formRef: FormInstance | undefined, _loginFrom: ILoginData) => {
    if (!_formRef) return
    _formRef.validate((_valid: boolean) => {
        if (_valid) {
            loading.value = true;
            _loginFrom.grant_type = "password";
            useAuthStore().login(_loginFrom)
                .then(() => {
                    
                    router.push("/home");
                })
                .catch(() => {
                    alert("登录跳转错误")
                })
                .finally(() => {
                    loading.value = false;
                })
        } else {
            return false
        }
    })

};

</script>
<template>
    <div class="loginForm flex-center ">
        <el-form ref="formRef" :model="loginForm" label-width="auto" style="width:260px" size="large" scroll-to-error>
            <el-form-item prop="username" :rules="[
            { required: true, message: $t('login.form.placeholder_username'), trigger: 'trigger' },
            { validator: noChinese, trigger: 'blur' },
        ]">
                <el-input v-model="loginForm.username" :prefix-icon="User"
                    :placeholder="$t(`login.form.input_username`)" />
            </el-form-item>
            <el-form-item prop="password" :rules="[
            { required: true, message: $t(`login.form.placeholder_password`), trigger: 'trigger' },
        ]">
                <el-input v-model="loginForm.password" type="password" :prefix-icon="Lock"
                    :placeholder="$t(`login.form.input_password`)" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" :loading="loading" style="width: 100%;" auto-insert-space
                    @click="loginChange(formRef, loginForm)">{{
            $t('login.login_in') }}</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<style lang='scss' scoped></style>